const financeSetting = require('../../../utils/finance-setting');
const app = getApp();

Page({
  data: {
    isAmountHidden: false,
    privacyProtect: false,
    // 收支类型
    financeTypeOptions:[
      { name: '收入', value: 'income' },
      { name: '支出', value: 'expense' }
    ],
    cycleDayOptions: Array.from({ length: 31 }, (_, i) => i + 1),
    cycleDayIndex: 0,
    place: '',
    budget: '',
    // 记账提醒相关
    remindCycleOptions: ['每天', '每周', '每月'],
    remindCycleIndex: 0,
    remindTime: '20:00',
    remindMethodOptions: [],
    remindMethods: [],
    userInfo: null,
    token: '',
    showPrivacyPwdModal: false,
    privacyPwdInput: '',
    pendingPrivacyProtect: false, // 记录是否要开启（不再使用）
    financeType: 'expense', // 默认支出类型
    financeTypeIndex: 1, // 默认支出类型索引
    familyMemberFinanceNotify: false,
    familyMemberExitNotify: false,
    familyMemberJoinNotify: false,
    // 每月固定模板执行提醒
    fixTemplateExecNotify: false,
    // 记账提醒是否开启， 默认是关闭
    financeRemindEnabled: false,
    // 默认记账账户相关
    accountList: [],
    accountIndex: -1,
    showAccountSelector: false,
    // 默认记账分类相关
    categoryList: [],
    incomeCategoryList: [],
    expenseCategoryList: [],
    categoryIndex: -1,
    categoryType: 'expense', // 默认支出类型
    showCategorySelector: false,
    // 支付方式相关
    paymentMethodList: [],
    paymentMethodIndex: -1,
  },
  async onLoad() {
    // 获取本地用户信息
    const userInfo = wx.getStorageSync('userInfo') || null;
    const token = wx.getStorageSync('token') || '';
    this.setData({ userInfo, token });
    
    // 初始化账户列表
    await this.initAccountList();
    
    await this.loadSetting();
  },
  async loadSetting() {
    wx.showLoading({ title: '加载中...' });
    try {
      const res = await financeSetting.settingInit();
      // 记账提醒方式选项和默认值
      const remindMethodOptions = (res.remindMethodList || []).filter(item => item.visible !== false);
      // 记账提醒json对象
      const financeRemindJson = res.data.financeRemind && res.data.financeRemind.jsonText ? JSON.parse(res.data.financeRemind.jsonText) : null;
      let remindMethods;
      if (Array.isArray(financeRemindJson?.method)) {
        remindMethods = financeRemindJson.method;
      } else {
        remindMethods = remindMethodOptions.filter(item => item.checked).map(item => item.value);
      }
      remindMethodOptions.forEach(item => {
        if (remindMethods.includes(item.value)) {
          item.checked = true;
        }
      });
      console.log('remindMethods', remindMethods);
      console.log('remindMethodOptions', remindMethodOptions)
      // 规范化支付方式列表，确保有可显示的 name，并过滤空项
      const rawPaymentMethodList = res.paymentMethodList || [];
      const normalizedPaymentMethodList = (rawPaymentMethodList || [])
        .map(item => ({
          ...item,
          name: (item && (item.name || item.paymentMethodName || item.label || item.text)) || ''
        }))
        .filter(item => item && item.name && item.name.trim().length > 0);

      // 计算默认支付方式索引
      let paymentMethodIndex = -1;
      if (res.data.defaultPaymentMethod?.jsonText) {
        const def = res.data.defaultPaymentMethod.jsonText;
        paymentMethodIndex = normalizedPaymentMethodList.findIndex(pm => pm.name === def);
      }
      // if (paymentMethodIndex === -1 && normalizedPaymentMethodList.length > 0) {
      //   paymentMethodIndex = 0;
      // }

      this.setData({
        isAmountHidden: res.data.hideAmount?.jsonText === 'true',
        privacyProtect: res.data.privacyProtect?.jsonText === 'true',
        cycleDayIndex: Math.max(0, (res.data.cycleDay?.jsonText || 1) - 1),
        place: res.data.defaultPlace?.jsonText || '',
        budget: res.data.monthExpenseBudget?.jsonText || '',
        // 记账提醒
        remindCycleOptions: res.cycleList || [],
        remindCycleIndex: financeRemindJson?.cycleCode ? res.cycleList?.findIndex(item => item.cycleCode === financeRemindJson.cycleCode) : 0,
        financeRemindEnabled: financeRemindJson ? true : false,
        remindTime: financeRemindJson?.time || '20:00',
        remindMethodOptions: remindMethodOptions,
        remindMethods: remindMethods,
        financeType: res.data.defaultFinanceType?.jsonText || 'expense',
        financeTypeIndex: res.data.defaultFinanceType?.jsonText === 'income' ? 0 : 1,
        familyMemberFinanceNotify: res.data.familyMemberFinanceNotify?.jsonText === 'true',
        familyMemberExitNotify: res.data.familyMemberExitNotify?.jsonText === 'true',
        familyMemberJoinNotify: res.data.familyMemberJoinNotify?.jsonText === 'true',
        fixTemplateExecNotify: res.data.fixTemplateExecNotify?.jsonText === 'true',
        // 默认记账账户
        accountIndex: res.data.defaultAccountBookId?.jsonText ? this.data.accountList.findIndex(item => item.id === res.data.defaultAccountBookId?.jsonText) : -1,
        // 默认记账分类
        categoryList: res.categoryList || [],
        incomeCategoryList: (res.categoryList || []).filter(item => item.type === 'income' || item.financeType === 'income'),
        expenseCategoryList: (res.categoryList || []).filter(item => item.type === 'expense' || item.financeType === 'expense'),
        categoryIndex: res.data.defaultCategoryCode?.jsonText ? (res.categoryList || []).findIndex(item => item.name === res.data.defaultCategoryCode?.jsonText) : -1,
        // 支付方式
        paymentMethodList: normalizedPaymentMethodList,
        paymentMethodIndex: paymentMethodIndex,
      });
      
      // 调试信息
      console.log('分类数据:', {
        categoryList: res.categoryList,
        incomeCategoryList: (res.categoryList || []).filter(item => item.type === 'income' || item.financeType === 'income'),
        expenseCategoryList: (res.categoryList || []).filter(item => item.type === 'expense' || item.financeType === 'expense'),
        defaultCategoryCode: res.data.defaultCategoryCode?.jsonText,
        categoryIndex: res.data.defaultCategoryCode?.jsonText ? (res.categoryList || []).findIndex(item => item.name === res.data.defaultCategoryCode?.jsonText) : -1
      });
    } catch (e) {
      console.log(e);
      wx.showToast({ title: (e && e.data && e.data.msg) || '加载失败', icon: 'none' });
      // 关闭
      setTimeout(() => {
        wx.navigateBack();
      }, 600);
    } finally {
      wx.hideLoading();
    }
  },
  
  // 初始化账户列表
  async initAccountList() {
    try {
      const { accountList } = await app.getAccountGlobal();
      console.log('账户列表:', accountList);
      console.log('账户列表长度:', accountList ? accountList.length : 0);
      if (accountList && accountList.length > 0) {
        console.log('第一个账户:', accountList[0]);
      }
      
      // 确保字段名与account-selector组件兼容
      const processedAccountList = accountList.map(account => ({
        ...account,
        name: account.accountName || account.name, // 确保有name字段
        description: account.description || '' // 确保有description字段
      }));
      
      this.setData({ accountList: processedAccountList });
    } catch (e) {
      console.error('获取账户列表失败:', e);
    }
  },
  onToggleAmountHidden(e) {
    const value = e.detail.value;
    this.setData({ isAmountHidden: value });
  },
  onTogglePrivacyProtect(e) {
    const checked = e.detail.value;
    // 直接生效，不再弹出密码框
    this.setData({ privacyProtect: checked, showPrivacyPwdModal: false, pendingPrivacyProtect: false });
  },
  onCycleDayChange(e) {
    const idx = e.detail.value;
    this.setData({ cycleDayIndex: idx });
  },
  onPlaceInput(e) {
    const value = e.detail.value;
    this.setData({ place: value });
  },
  onBudgetInput(e) {
    let value = e.detail.value.replace(/[^\d.]/g, '');
    if (value && !/^\d+(\.\d{0,2})?$/.test(value)) {
      value = value.replace(/(\.\d{2})\d+/, '$1');
    }
    this.setData({ budget: value });
  },
  onBudgetBlur(e) {
    let value = e.detail.value.replace(/[^\d.]/g, '');
    if (value && !/^\d+(\.\d{0,2})?$/.test(value)) {
      value = value.replace(/(\.\d{2})\d+/, '$1');
    }
    this.setData({ budget: value });
  },
  onRemindCycleChange(e) {
    const idx = e.detail.value;
    this.setData({ remindCycleIndex: idx });
  },
  onRemindTimeChange(e) {
    const time = e.detail.value;
    this.setData({ remindTime: time });
  },
  onRemindMethodChange(e) {
    // 先重置所有为未选中
    const options = this.data.remindMethodOptions.map(item => ({ ...item, checked: false }));
    // 再将选中的设为true
    const selected = new Set(e.detail.value);
    options.forEach(item => {
      if (selected.has(item.value)) item.checked = true;
    });
    this.setData({
      remindMethods: Array.from(selected),
      remindMethodOptions: options
    });
  },
  onAiTypeChange(e) {
    const selectedIndex = e.detail.value;
    const selectedType = this.data.financeTypeOptions[selectedIndex].value;
    this.setData({ 
      financeType: selectedType,
      financeTypeIndex: selectedIndex,
      categoryIndex: -1 // 重置分类选择
    });
  },
  // 选择默认支付方式
  onPaymentMethodChange(e) {
    const idx = Number(e.detail.value);
    this.setData({ paymentMethodIndex: idx });
  },
  onFamilyMemberFinanceNotifyChange(e) {
    this.setData({ familyMemberFinanceNotify: e.detail.value });
  },
  onFamilyMemberExitNotifyChange(e) {
    this.setData({ familyMemberExitNotify: e.detail.value });
  },
  onFamilyMemberJoinNotifyChange(e) {
    this.setData({ familyMemberJoinNotify: e.detail.value });
  },
  // 每月固定模板执行提醒
  onFixTemplateExecNotifyChange(e) {
    this.setData({ fixTemplateExecNotify: e.detail.value });
  },
  // 记账提醒是否开启
  onFinanceRemindEnabledChange(e) {
    this.setData({ financeRemindEnabled: e.detail.value });
  },
  
  // 显示账户选择器
  showAccountSelector() {
    console.log('显示账户选择器');
    console.log('账户列表:', this.data.accountList);
    console.log('账户列表长度:', this.data.accountList ? this.data.accountList.length : 0);
    this.setData({ showAccountSelector: true });
  },
  
  // 隐藏账户选择器
  hideAccountSelector() {
    this.setData({ showAccountSelector: false });
  },
  
  // 选择账户
  onSelectAccount(e) {
    const idx = e.detail.index;
    this.setData({
      accountIndex: idx,
      showAccountSelector: false
    });
  },
  
  // 显示分类选择器
  showCategorySelector() {
    this.setData({ showCategorySelector: true });
  },
  
  // 隐藏分类选择器
  hideCategorySelector() {
    this.setData({ showCategorySelector: false });
  },
  
  // 选择分类
  onCategorySelect(e) {
    const { index, type, item } = e.detail;
    // 在 categoryList 中查找对应项
    const categoryList = this.data.categoryList;
    const originalIndex = categoryList.findIndex(cat => cat.id === item.id);
    this.setData({
      categoryIndex: originalIndex,
      categoryType: type,
      showCategorySelector: false
    });
  },
  
  // 清除分类选择
  onClearCategory() {
    this.setData({ categoryIndex: -1 });
  },
  /**
   * 提交操作
   */
  async onSubmitSetting() {
    const paramArray = [];
    paramArray.push({'settingCode': 'hideAmount', 'jsonText': this.data.isAmountHidden});
    paramArray.push({'settingCode': 'privacyProtect', 'jsonText': this.data.privacyProtect });
    paramArray.push({'settingCode': 'cycleDay', 'jsonText': this.data.cycleDayOptions[this.data.cycleDayIndex] });
    paramArray.push({'settingCode': 'defaultPlace', 'jsonText': this.data.place });
    paramArray.push({'settingCode': 'monthExpenseBudget', 'jsonText': this.data.budget });
    // 记账提醒
    if (this.data.financeRemindEnabled) {
      // 校验提醒周期、提醒时间、提醒方式
      if (
        !this.data.remindCycleOptions ||
        !this.data.remindCycleOptions[this.data.remindCycleIndex] ||
        !this.data.remindCycleOptions[this.data.remindCycleIndex].cycleCode
      ) {
        wx.showToast({ title: '请选择提醒周期', icon: 'none' });
        return;
      }
      if (!this.data.remindTime) {
        wx.showToast({ title: '请选择提醒时间', icon: 'none' });
        return;
      }
      if (!this.data.remindMethods || this.data.remindMethods.length === 0) {
        wx.showToast({ title: '请选择提醒方式', icon: 'none' });
        return;
      }
      const remindCycleCode = this.data.remindCycleOptions[this.data.remindCycleIndex].cycleCode;
      paramArray.push({'settingCode': 'financeRemind', 'jsonText': {'cycleCode': remindCycleCode, 'time': this.data.remindTime, 'method': this.data.remindMethods} });
    }
    paramArray.push({'settingCode': 'defaultFinanceType', 'jsonText': this.data.financeType });
    paramArray.push({'settingCode': 'familyMemberFinanceNotify', 'jsonText': this.data.familyMemberFinanceNotify});
    paramArray.push({'settingCode': 'familyMemberExitNotify', 'jsonText': this.data.familyMemberExitNotify});
    paramArray.push({'settingCode': 'familyMemberJoinNotify', 'jsonText': this.data.familyMemberJoinNotify});
    paramArray.push({'settingCode': 'fixTemplateExecNotify', 'jsonText': this.data.fixTemplateExecNotify});
    // 默认记账账户
    if (this.data.accountIndex >= 0 && this.data.accountList[this.data.accountIndex]) {
      paramArray.push({'settingCode': 'defaultAccountBookId', 'jsonText': this.data.accountList[this.data.accountIndex].id });
    }
    // 默认记账分类
    if (this.data.categoryIndex >= 0 && this.data.categoryList[this.data.categoryIndex]) {
      paramArray.push({'settingCode': 'defaultCategoryCode', 'jsonText': this.data.categoryList[this.data.categoryIndex].name });
    }
    // 默认支付方式
    if (this.data.paymentMethodIndex >= 0 && this.data.paymentMethodList[this.data.paymentMethodIndex]) {
      const sel = this.data.paymentMethodList[this.data.paymentMethodIndex];
      // 优先保存 code，兼容没有 code 的情况保存 name
      paramArray.push({'settingCode': 'defaultPaymentMethod', 'jsonText': sel.code || sel.name });
    }
    // 你可以继续添加其他设置项
    try {
      await financeSetting.submitSetting({jsonText: JSON.stringify(paramArray)});
      wx.showToast({ title: '已保存', icon: 'success', duration: 600 });
      setTimeout(() => {
        wx.navigateBack();
      }, 600);
    } catch (e) {
      console.log(e);
      wx.showToast({ title: (e && e.data && e.data.msg) || '提交失败', icon: 'none' });
    }
  },
  onCategoryManage() {
    wx.navigateTo({ url: '/pages/finance/profile/category/category' });
  },
  onAccountManage() {
    wx.navigateTo({ url: '/pages/finance/profile/account/account' });
  },
  onExport() {
    wx.navigateTo({ url: '/pages/finance/export/export' });
  },
  onLogout() {
    wx.navigateTo({ url: '/pages/finance/logout/logout' });
  },
  onProfile() {
    wx.navigateTo({ url: '/pages/my-setting/my-setting' });
  },
  onProfileCenter() {
    wx.navigateTo({ url: '/pages/finance/profile-center/profile-center' });
  },
});